import React from 'react';
import { Icon } from '@ant-design/compatible';
import moment from 'moment';
import 'moment/locale/zh-cn';
import pinyin from './pinyin';

moment.locale('zh-cn');

// 工具集
const tools = {
  // 获取今天的日期字符串
  funcToday(incTime = false, date = new Date()) {
    const yy = date.getFullYear();
    let mm = date.getMonth() + 1;
    let dd = date.getDate();

    mm = mm < 10 ? '0' + mm : mm;
    dd = dd < 10 ? '0' + dd : dd;

    let str = yy + '-' + mm + '-' + dd;

    if (incTime) {
      let hh = date.getHours();
      let m2 = date.getMinutes();

      hh = hh < 10 ? '0' + hh : hh;
      m2 = m2 < 10 ? '0' + m2 : m2;

      str += ' ' + hh + ':' + m2;
    }

    return str;
  },
  // 获取当前时间
  funcNow(hour = false, zero = true) {
    const d = new Date();
    let hh = d.getHours();
    let mm = d.getMinutes();
    let ss = d.getSeconds();

    if (zero) {
      hh = hh < 10 ? '0' + hh : hh;
      mm = mm < 10 ? '0' + mm : mm;
      ss = ss < 10 ? '0' + ss : ss;
    }

    let str = hh;

    if (!hour) str += ':' + mm + ':' + ss;

    return str;
  },
  // 获取今年元旦
  funcGetYYYY0101() {
    const d = new Date();
    const yy = d.getFullYear();
    return yy + '-01-01';
  },
  // 获取本月月初
  funcGetYYYYMM01() {
    const d = new Date();
    const yy = d.getFullYear();
    let mm = d.getMonth() + 1;
    mm = mm < 10 ? '0' + mm : mm;
    return yy + '-' + mm + '-01';
  },
  // 获取明年
  funcGetNextYear() {
    const d = new Date();
    const yy = d.getFullYear() + 1;
    let mm = d.getMonth() + 1;
    let dd = d.getDate();
    mm = mm < 10 ? '0' + mm : mm;
    dd = dd < 10 ? '0' + dd : dd;
    return yy + '-' + mm + '-' + dd;
  },
  // 获取下月
  funcGetNextMonth(dateStr = '') {
    const d = dateStr === '' ? new Date() : new Date(dateStr);
    let yy = d.getFullYear();
    let mm = d.getMonth() + 2;
    if (mm === 13) {
      mm = 1;
      yy += 1;
    }
    mm = mm < 10 ? '0' + mm : mm;
    return yy + '-' + mm + '-01';
  },
  // 获取月底
  funcGetLastMonthDay(dateStr = tools.funcToday()) {
    let yy = parseInt(dateStr.substr(0, 4), 10);
    let mm = parseInt(dateStr.substr(5, 2), 10);
    mm += 1;
    if (mm === 13) {
      mm = 1;
      yy += 1;
    }
    if (mm < 10) mm = '0' + mm;
    let date1 = yy + '-' + mm + '-01';
    date1 = this.funcGetDay(-1, date1);
    return date1;
  },
  // 获取某一天(例如昨天或者明天)
  funcGetDay(num, dateStr = '', incTime = false) {
    let ts = this.funcGetTimestampByDate(dateStr);
    ts += num * 86400;
    return this.funcGetDateByTimestamp(ts, incTime);
  },
  // 获取某一小时(例如下一小时)
  funcGetDayAndTime(num, dateStr = '', incTime = false) {
    let ts = this.funcGetTimestampByDate(dateStr);
    ts += num * 3600;
    return this.funcGetDateByTimestamp(ts, incTime);
  },

  // 根据日期字符串取时间戳
  funcGetTimestampByDate(dateStr) {
    const d = !dateStr ? new Date() : new Date(dateStr.substr(0, 10));
    let timestamp = d.getTime();
    timestamp /= 1000;
    timestamp = parseInt(timestamp, 10);
    return timestamp;
  },

  // 根据时间戳取日期字符串
  funcGetDateByTimestamp(ts, incTime = false) {
    const tsNum = ts * 1000;
    let strDay = '';
    const tsNum2 = tsNum + '';
    if (tsNum2.length !== 13) {
      strDay = this.funcToday();
    } else {
      const d = new Date(tsNum);
      const yy = d.getFullYear();
      let mm = d.getMonth() + 1;
      let dd = d.getDate();

      mm = mm < 10 ? '0' + mm : mm;
      dd = dd < 10 ? '0' + dd : dd;
      strDay = yy + '-' + mm + '-' + dd;

      if (incTime) {
        let hh = d.getHours();
        let m2 = d.getMinutes();

        hh = hh < 10 ? '0' + hh : hh;
        m2 = m2 < 10 ? '0' + m2 : m2;

        strDay += ' ' + hh + ':' + m2;
      }
    }

    return strDay;
  },

  // 获取本周范围
  funcGetWeek(dateStr = '') {
    const d = dateStr === '' ? new Date() : new Date(dateStr);
    let week = d.getDay();
    if (week === 0) week = 7;
    week -= 1;
    let timestamp = d.getTime();
    timestamp /= 1000;
    timestamp = parseInt(timestamp, 10);
    const ts0 = timestamp - week * 86400;
    const ts1 = timestamp + (6 - week) * 86400;
    const { funcGetDateByTimestamp } = this;
    const date0 = funcGetDateByTimestamp(ts0) + ' 00:00:00';
    const date1 = funcGetDateByTimestamp(ts1) + ' 23:59:59';
    return { startDate: date0, endDate: date1 };
  },

  // 获取一个随机数(取毫秒)
  funcRand() {
    const now = new Date();
    return now.getMilliseconds();
  },

  // 格式化手机号(中间加空格)
  funcPhoneSpace(value) {
    if (value === '' || value === undefined || value == null || window.isNaN(value)) return '';
    let val2 = value;
    if (value.length >= 4) val2 = value.substr(0, 3) + ' ' + value.substr(3, 4);
    if (value.length >= 8) val2 += ' ' + value.substr(7, 4);
    return val2;
  },

  // 设置cookie
  funcSetCookie(name, value) {
    const day = 7; // 有效期
    const exp = new Date();
    exp.setTime(exp.getTime() + day * 24 * 60 * 60 * 1000);
    document.cookie = name + '=' + escape(value) + ';expires=' + exp.toGMTString();
  },
  // 获取cookie
  funcGetCookie(name) {
    if (document.cookie.length > 0) {
      let start = document.cookie.indexOf(name + '=');
      if (start >= 0) {
        start = start + name.length + 1;
        let end = document.cookie.indexOf(';', start);
        if (end === -1) end = document.cookie.length;
        return unescape(document.cookie.substring(start, end));
      }
    }
    return '';
  },
  // 删除cookie
  funcDelCookie(name) {
    const exp = new Date();
    exp.setTime(exp.getTime() - 1);
    const cval = this.funcGetCookie(name);
    if (cval != null) document.cookie = name + '=' + cval + ';expires=' + exp.toGMTString();
  },

  // 把值写入本地存储
  funcSetLocalValue(name, value) {
    sessionStorage.setItem(name, value);
  },
  // 获取本地存储的值
  funcGetLocalValue(name) {
    return sessionStorage.getItem(name) || '';
  },
  // 删除某一个本地存储
  funcDelLocalValue(name) {
    sessionStorage.removeItem(name);
  },

  // 获取访问令牌
  funcGetToken() {
    return this.funcGetLocalValue('token');
  },
  // 获取用户ID
  funcGetUserId() {
    return parseInt(this.funcGetLocalValue('userId') || '0', 10);
  },

  // 获取对象成员个数
  funcGetObjNum(obj) {
    let count = 0;
    for (const i in obj) {
      count += 1;
    }
    return count;
  },

  // 对话框的标题带图标
  funcDlgTitle(title, act, appendInfo) {
    let type = 'file-add';
    let stat = '新增';
    let info = '信息';
    if (act === 'edit') {
      type = 'edit';
      stat = '编辑';
    }
    if (!appendInfo) info = '';

    return (
      <div>
        <Icon type={type} style={{ fontSize: 16 }} />
        <span> {stat + title + info}</span>
      </div>
    );
  },

  // id,pid(列表结构)转children(树形结构)
  funcPidToChildren(arr, id, pid, children, selectable = false) {
    // 参考自: pid的数据结构转children数据结构
    // https://www.cnblogs.com/hanhaihu/p/10114587.html
    if (!id) id = 'id';
    if (!pid) pid = 'pid';
    if (!children) children = 'children';

    const r = [];
    const hash = {};
    for (let i = 0; i < arr.length; i += 1) {
      hash[arr[i][id]] = arr[i];
    }
    for (let j = 0; j < arr.length; j += 1) {
      const aVal = arr[j];
      const hashVP = hash[aVal[pid]];
      if (hashVP) {
        !hashVP[children] && (hashVP[children] = []);
        hashVP[children].push(aVal);
        if (hashVP[children]) hashVP.selectable = selectable;
      } else r.push(aVal);
    }
    return r;
  },

  // 检查资源(功能)是否可用
  funcCheckValid(props, resName, pageName) {
    const { pathname } = props.location;
    const resPath = pageName ?
      pathname.split('/')[1] + '/' + pageName + '/' + resName :
      pathname.substr(1) + '/' + resName;
    const { resData } = props.menu;
    return resData.indexOf(resPath) >= 0;
  },

  // 简单加密一个字符串
  funcEncrypt(text = '') {
    let str = text.toUpperCase();
    str = pinyin.getCamelChars(str);
    const mappingNum = 'OIZEASGTBP';
    const arr = str.split('').reverse()
      .map(char => mappingNum.indexOf(char) >= 0 ? mappingNum.indexOf(char) : char);
    str = arr.join('').toLowerCase();
    return str;
  },
};
export default tools;
